#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""
读取文本解析节点
"""

from lxml import etree

text = '''
<div>
    <ul>
         <li class="item-0"><a href="link1.html">第一个</a><br/>double</li>
         <li class="item-1"><a href="link2.html">second item</a></li>
         <li class="item-2"><a href="link5.html">a属性</a>
     </ul>
 </div>
'''


def main():
    """
    测试
    :return:
    """
    # 初始化生成一个XPath解析对象
    html = etree.HTML(text)
    # 解析对象输出
    result = etree.tostring(html, encoding='UTF-8')
    print(type(html))
    print(type(result))
    print("result = ", result.decode('UTF-8'))  # 会自动补上<html>标签

    print("*" * 40)
    # 获取某个子节点的父节点
    result = html.xpath('//a[@href="link1.html"]/parent::*/@class')  # 通过parent::*来查找父节点
    print(result)
    result = html.xpath('//a[@href="link1.html"]/../@class')    # 通过..来查找父节点
    print(result)

    print("*" * 40)
    # 用@符号进行属性过滤
    result = html.xpath('//li[@class="item-1"]')
    print(result)

    print("*" * 40)
    # 用text()方法获取节点中的文本
    result = html.xpath('//li[@class="item-0"]/a/text()')
    print(result)
    result = html.xpath('//li[@class="item-0"]//text()')    # 获取li下所有子孙节点的内容
    print(result)

    print("*" * 40)
    # 获取所有li节点的子孙节点的href属性
    result = html.xpath("//li//@href")
    print(result)

    print("*" * 40)
    # 获取第一个li节点的子孙节点的href属性
    result = html.xpath("//li[1]//@href")
    print(result)
    # 获取第2个li节点的子孙节点的href属性
    result = html.xpath("//li[2]//@href")
    print(result)


if __name__ == '__main__':
    main()
